package com.example.muasic.fragment;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bilibili.magicasakura.utils.ThemeUtils;
import com.bilibili.magicasakura.widgets.TintImageView;
import com.bilibili.magicasakura.widgets.TintProgressBar;
import com.example.muasic.MainApplication;
import com.example.muasic.R;
import com.example.muasic.activity.MainActivity;
import com.example.muasic.activity.PlayMusicActivity;
import com.example.muasic.activity.PlayingActivity;
import com.example.muasic.handler.HandlerUtil;
import com.example.muasic.info.Info;
import com.example.muasic.provider.MusicSqLiteHelper;
import com.example.muasic.service.IService;
import com.example.muasic.service.MusicPlayer;
import com.example.muasic.service.MusicService;
import com.example.muasic.uitl.utils;
import com.facebook.common.logging.FLog;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.image.QualityInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;

import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static android.content.Context.BIND_AUTO_CREATE;
import static com.example.muasic.activity.PlayingActivity.playing;

public class QuickControlsFragment extends BaseFragment {


    private ProgressBar mProgress;
    public Runnable mUpdateProgress = new Runnable() {

        @Override
        public void run() {

            long position = MusicPlayer.position();
            long duration = MusicPlayer.duration();
            if (duration > 0 && duration < 627080716){
                mProgress.setProgress((int) (1000 * position / duration));
            }

            if (MusicPlayer.isPlaying()) {
                mProgress.postDelayed(mUpdateProgress, 50);
            }else {
                mProgress.removeCallbacks(mUpdateProgress);
            }

        }
    };
    private static ImageView mPlayPause;
    private static IService iService;
    private ServiceConnection conn;
    private MusicSqLiteHelper musicSqLiteHelper;
    private static TextView mTitle;
    private static TextView mArtist;
    private static ImageView mpic;
    private static int position;
    private static int playing;
    private static Context context;
    private static SimpleDraweeView mAlbumArt;
    private View rootView;
    private ImageView playQueue, next;
    private String TAG = "QuickControlsFragment";
    private static QuickControlsFragment fragment;
    private static List<String> titleList = new ArrayList<>();
    private static List<Info> musicList = new ArrayList<>();

    public static QuickControlsFragment newInstance() {
        return new QuickControlsFragment();
    }


    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Fresco.initialize(this.getActivity());
        View rootView = inflater.inflate(R.layout.bottom_nav, container, false);
        this.rootView = rootView;


        View cv = getActivity().getWindow().getDecorView();
        context=cv.getContext();

        // 开启服务
        Intent intent = new Intent(getActivity(), MusicService.class);
        this.getActivity().startService(intent);
        conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                //6. 获取IBinder对象, 以此调用暴露的函数
                iService = (IService) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        };

        //绑定服务

        this.getActivity().bindService(intent, conn, BIND_AUTO_CREATE);
        position = ((MainActivity) getActivity()).getNowPosition();


        titleList = ((MainActivity) getActivity()).gettitleList();
        musicList = ((MainActivity) getActivity()).getNowmusicList();
        mPlayPause = (ImageView) rootView.findViewById(R.id.control);
        mProgress = (ProgressBar) rootView.findViewById(R.id.song_progress_normal);
        mTitle = (TextView) rootView.findViewById(R.id.playbar_info);
        mArtist = (TextView) rootView.findViewById(R.id.playbar_singer);
       //mAlbumArt = (SimpleDraweeView) rootView.findViewById(R.id.playbar_img);
        mpic=(ImageView) rootView.findViewById(R.id.playbar_img);
        next = (ImageView) rootView.findViewById(R.id.play_next);
        playQueue = (ImageView) rootView.findViewById(R.id.play_list);

        mProgress.setProgressTintList(ThemeUtils.getThemeColorStateList(mContext, R.color.theme_color_primary));
        mProgress.postDelayed(mUpdateProgress, 0);

        mPlayPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mintent = new Intent(getActivity(), MusicService.class);
                Log.i("auhsbd", "cggggggg" + playing);
                if (playing == 0) {
                    position=iService.callgetNowMusic();
                    if(position<0)
                    {
                        position=0;
                        iService.callNowMusic(position);
                    }
                  /*  mPlayPause.setImageResource(R.drawable.playbar_btn_pause);
                    PlayMusicActivity playMusicActivity=new PlayMusicActivity();
                    playMusicActivity.bindService(mintent,conn,BIND_AUTO_CREATE);
                    iService.callPlayMusic(musicList.get(position).getData());*/
                    Log.i("auhsbd", "srtrttttttt" + playing);

                    playing = 1;
                } else if (playing == 1) {
                    mPlayPause.setImageResource(R.drawable.playbar_btn_play);
                    iService.callPauseMusic();
                    playing = 2;
                }else if(playing == 2){
                    mPlayPause.setImageResource(R.drawable.playbar_btn_pause);
                    iService.callConMusic();
                    playing = 1;
                }
            }
        });



        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                position++;
                iService.callNowMusic(position);
                iService.callPlayMusic(musicList.get(position).getData());
                updateNowplayingCard();


            }
        });

        playQueue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        PlayQueueFragment playQueueFragment = new PlayQueueFragment();
                        playQueueFragment.show(getFragmentManager(), "playqueuefragment");
                    }
                }, 60);

            }
        });

        rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Bundle bundle = new Bundle();
                position=iService.callgetNowMusic();
                if(iService.callgetNowMusic()<0||iService.callgetNowMusic()>=musicList.size()) {
                    position=0;
                    playing(musicList.get(position).getData(), iService);
                    iService.callgetNowmusicList(musicList);
                    iService.callNowMusic(position);
                }else {
                    long nowMusicId=iService.callgetNowMusicId();
                    if (nowMusicId != musicList.get(position).getSongId()) {
                        playing(musicList.get(position).getData(), iService);
                        iService.callgetNowmusicList(musicList);
                        iService.callNowMusic(position);
                    }
                }
                Intent intent = new Intent(mContext,
                        PlayingActivity.class);
                bundle.putInt("music_send",position);
                bundle.putSerializable("musiclist", (Serializable) musicList);
                intent.putExtras(bundle);
                startActivity(intent);

//                Intent intent = new Intent(mContext, PlayingActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
            }
        });




        return rootView;
    }

    public static void setPosition(int Pos){
        position=Pos;
    }

    public static void setpalying(int Pos){
        playing=Pos;
    }


    public static void setmusicList(List<Info> setmusicList){
        musicList=setmusicList;
    }

    public static void updateNowplayingCard() {
        Bitmap bitmap = null;
        if(position<0||position>=musicList.size()) {
            position=0;
            try {
                bitmap = utils.getAlbumArt(context,musicList.get(position).getAlbumId());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }else {

            try {
                bitmap = utils.getAlbumArt(context, musicList.get(position).getAlbumId());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        if (playing == 0) {
            if(position<0)
            {
                position=0;
            }
            Log.i("auhsbd", "srtrttttttt" + playing);
            mPlayPause.setImageResource(R.drawable.playbar_btn_play);

        } else if (playing == 1) {
            mPlayPause.setImageResource(R.drawable.playbar_btn_pause);

        }else if(playing == 2){
            mPlayPause.setImageResource(R.drawable.playbar_btn_play);
        }
        mpic.setImageBitmap(bitmap);
        mTitle.setText(musicList.get(position).getMusicName());
        mArtist.setText(musicList.get(position).getArtist());
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onStop() {
        super.onStop();
        mProgress.removeCallbacks(mUpdateProgress);
    }

    @Override
    public void onResume() {
        super.onResume();
        mProgress.setMax(1000);
        mProgress.removeCallbacks(mUpdateProgress);
        mProgress.postDelayed(mUpdateProgress,0);
        updateNowplayingCard();

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void updateState() {

        /*MusicPlayer.isPlaying()*/
        if (MusicPlayer.isPlaying()) {
            mPlayPause.setImageResource(R.drawable.playbar_btn_pause);
//            mPlayPause.setImageTintList(R.color.theme_color_primary);
            mProgress.removeCallbacks(mUpdateProgress);
            mProgress.postDelayed(mUpdateProgress,50);
        } else {
            mPlayPause.setImageResource(R.drawable.playbar_btn_play);
//            mPlayPause.setImageTintList(R.color.theme_color_primary);
            mProgress.removeCallbacks(mUpdateProgress);
        }
    }


    public void updateTrackInfo() {
        updateNowplayingCard();
        updateState();
    }


    @Override
    public void changeTheme() {
        super.changeTheme();
        mProgress.setProgressTintList(ThemeUtils.getThemeColorStateList(mContext, R.color.theme_color_primary));
    }


}